import { loadMicroApp, initGlobalState, MicroAppStateActions } from 'qiankun';
import React, { createRef } from 'react';
import { connect } from 'umi';
const connectOrnament: any = connect;
import WujieReact from 'wujie-react';

@connectOrnament(({ common }: any) => ({ common }))
class Microapp extends React.Component {
  containerRef = React.createRef();
  microApp = null;

  componentWillUnmount() {
    if ((this as any).props.common.presentApp.appName !== 'wanfeng-app9') {
      const state = {
        microAppLoading: true,
      };

      // 初始化 state
      const actions: MicroAppStateActions = initGlobalState(state);

      actions.onGlobalStateChange((state, prev) => {
        // state: 变更后的状态; prev 变更前的状态
        console.log(state, prev);
      });
      actions.setGlobalState(state);
      actions.offGlobalStateChange();

      (this as any).microApp.unmount();
    }
  }

  render() {
    if ((this as any).props.common.presentApp.appName === 'wanfeng-app9') {
      return (
        <WujieReact
          width="100%"
          height="100%"
          name={(this as any).props.common.presentApp.appName}
          url={(this as any).props.common.presentApp.url}
          sync={false}
        />
      );
    }
    else if ((this as any).props.common.presentApp.appName) {
      (this as any).microApp = loadMicroApp({
        name: (this as any).props.common.presentApp.appName,
        entry: (this as any).props.common.presentApp.url,
        container: '#container',
        props: { brand: 'qiankun' },
      });
    }
    return <div id="container"></div>;
  }
}

export default Microapp;
